<template>
  <div
    ref="sliderContainer"
    class="slider-verify-container"
    @mousemove="onMouseMove"
    @mouseup="onMouseUp"
    @mouseleave="onMouseLeave"
  >
    <span v-if="blockState === 0" style="color: #000">请按住滑块，拖动到最右边</span>
    <div :style="{ left: leftP }" class="slider-verify-block" @mousedown="onMouseDown">
      <el-icon size="20" color="#969CAD"><DArrowRight /></el-icon>
    </div>
    <div :style="{ width: leftP }" class="slider-verify-complete">
      <span v-if="blockState === 2">验证成功</span>
    </div>
  </div>
</template>

<script setup>
import { ref, defineEmits } from "vue";

const emit = defineEmits(["success", "failed"]);

const leftP = ref("0");

const blockState = ref(0);

const startP = ref(undefined);

const sliderContainer = ref(undefined);
const onMouseDown = (e) => {
  if (blockState.value !== 2) {
    leftP.value = "0";
    blockState.value = 1;
    startP.value = {
      clientX: e.clientX,
    };
  } else {
    leftP.value = "0";
    blockState.value = 0;
  }
};
const onMouseMove = (e) => {
  if (blockState.value === 1) {
    let width = e.clientX - startP.value.clientX;
    if (width + 54 > 417) {
      leftP.value = 417 - 54 + "px";
      blockState.value = 2;
      emit("success");
    } else {
      leftP.value = width + "px";
    }
  }
};
const onMouseUp = (e) => {
  if (blockState.value !== 2) {
    leftP.value = "0";
    blockState.value = 0;
    emit("failed");
  }
};
const onMouseLeave = (e) => {
  if (blockState.value !== 2) {
    leftP.value = "0";
    blockState.value = 0;
    emit("failed");
  }
};
</script>

<style lang="scss" scoped>
.slider-verify-container {
  position: relative;
  width: 100%;
  height: 40px;
  line-height: 40px;
  color: #cdd0d6;
  text-align: center;
  user-select: none;
  user-select: none;
  user-select: none;
  user-select: none;
  background-color: transparent;
  border: solid 1px #dcdfe6;
}

.slider-verify-complete {
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 40px;
  color: #fff;
  background-color: rgb(49 185 132);
}

.slider-verify-block {
  position: absolute;
  top: -1px;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 54px;
  height: 40px;
  // background-image: url("@/assets/images/login6/arrow.png");
  background-color: #fff;
  background-repeat: no-repeat;
  background-position: center;
  background-size: 50%;
  border: solid 1px #dcdfe6;
}
</style>
